<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <title>后台</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}" href="../../../../static/layui/css/layui.css"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
          integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div th:replace="/admin/share/_header :: header"></div>

    <!-- 左侧导航区域 -->
    <div th:replace="/admin/sys_mgt/share/_left_sidebar :: leftSidebar('role')"></div>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <div class="layui-tab">
                <ul class="layui-tab-title">
                    <li>角色管理</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
                            <div class="btn-group mr-2" role="group" aria-label="First group">
                                <button type="button" class="btn btn-secondary" data-toggle="modal"
                                        data-target="#saveRoleModal">
                                    <i class="layui-icon">&#xe608;</i> 添加
                                </button>
                            </div>
                            <div class="btn-group mr-2" role="group" aria-label="Second group">
                                <button type="button" class="btn btn-secondary" onclick="checkRoleAuth();">
                                    <!-- 选中的资源都属于那些权限 -->
                                    <i class="layui-icon">&#xe705;</i> 查看选中角色的权限
                                </button>
                            </div>
                        </div>
                        <!-- <th lay-data="{field:'id', width:60, sort: true, fixed: true}">ID</th> -->
                        <table class="layui-table" id="roleTable" lay-filter="roleTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增或者修改Role -->
    <div class="modal fade" id="saveRoleModal" tabindex="-1" role="dialog" aria-labelledby="saveRoleModalLabel"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="saveRoleModalLabel">新增角色</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="saveRoleForm" action="/admin/roles">
                        <div class="form-group">
                            <label for="name" class="col-form-label">角色名称:</label>
                            <input type="text" class="form-control" name="name" id="name"/>
                        </div>
                        <div class="form-group">
                            <label for="roleKey" class="col-form-label">角色-KEY:</label>
                            <input type="text" class="form-control" name="roleKey" id="roleKey"/>
                        </div>
                        <div class="form-group">
                            <label for="description" class="col-form-label">角色描述:</label>
                            <textarea class="form-control" name="description" id="description"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="remark" class="col-form-label">备注:</label>
                            <textarea class="form-control" name="remark" id="remark"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveRole();">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 角色对应权限 -->
    <div class="modal fade" id="roleAuthModal" tabindex="-1" role="dialog" aria-labelledby="roleAuthModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document" style="max-width: 1000px;">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="roleAuthModalLabel">角色权限</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="roleAuthContent">
                </div>
            </div>
        </div>
    </div>

    <!-- 
		th:insert  ：保留自己的主标签，保留th:fragment的主标签。
		th:replace ：不要自己的主标签，保留th:fragment的主标签。
		th:include ：保留自己的主标签，不要th:fragment的主标签。（官方3.0后不推荐）
	 -->
    <div th:replace="/admin/share/_footer :: footer"></div>
</div>

<script type="text/html" id="roleOps">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<script th:src="@{/layui/layui.js}" src="../../../../static/layui/layui.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/popper.js/1.12.3/umd/popper.min.js"
        integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh"
        crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
        integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
        crossorigin="anonymous"></script>

<script type="text/javascript">
    //JavaScript代码区域
    layui.use(['element', 'table', 'layer'], function () {
        var element = layui.element, layer = layui.layer, table = layui.table;

        table.render({
            elem: '#roleTable',
            height: 400,
            url: '/admin/roles/all',
            request: {
                pageName: 'page',
                limitName: 'size'
            },
            response: {
                dataName: 'rows',
                countName: 'totalCount'
            },
            page: true,
            cols: [
                [
                    {type: 'numbers', fixed: true},
                    {type: 'checkbox', fixed: true},
                    {field: 'name', width: 100, title: '角色用户'},
                    {field: 'roleKey', width: 150, title: 'ROLE-KEY'},
                    {field: 'description', title: '描述'},
                    {field: 'remark', title: '备注'},
                    {fixed: 'right', align: 'center', toolbar: '#roleOps'}
                ]
            ]
        });

        // 监听工具条
        table.on('tool(roleTable)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    delRole(obj, index);
                });
            } else if (layEvent === 'edit') {
                var saveRoleForm = document.getElementById("saveRoleForm");
                saveRoleForm.dataset.op = "update";
                saveRoleForm.dataset.roleId = data.id;
                for (var key in data) { // 为form表单load初始值
                    saveRoleForm[key].value = data[key];
                }
                $('#saveRoleModal').modal('show');
            }
        });

        /*  table.on('checkbox(roleTable)', function(obj) {
                 if(obj.checked && obj.data) { //
                       console.log(obj.checked); //当前是否选中状态
                       console.log(obj.data); //选中行的相关数据
                       console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
                 }
             }); */
    });

    // 为modal添加show 监听
    $('#saveRoleModal').on('show.bs.modal', function (event) {
        // event.target === this ： 均指modal ；event.relatedTarget： 谁触发了show modal事件
        var saveRoleForm = this.querySelector('#saveRoleForm');
        var saveRoleModalLabel = this.querySelector('#saveRoleModalLabel');
        if (saveRoleForm.dataset.op == 'update') {
            saveRoleModalLabel.innerHTML = "修改资源";
            saveRoleForm.method = "put";
        } else {
            saveRoleModalLabel.innerHTML = "新增资源";
            saveRoleForm.method = "post";
        }
    });

    // 为modal添加hide 监听
    $('#saveRoleModal').on('hide.bs.modal', function (event) {
        // event.target === this ： 均指modal ；event.relatedTarget： 谁触发了show modal事件，没有则为undefined
        var saveRoleForm = this.querySelector('#saveRoleForm');
        saveRoleForm.dataset.op = "add";
        saveRoleForm.reset(); // 重置form表单
    });

    var selectedRole;

    function checkRoleAuth() {
        var checkStatus = layui.table.checkStatus('roleTable'); //test即为基础参数id对应的值
        console.log(checkStatus.data) //获取选中行的数据
        if (checkStatus.data.length > 1) {
            layui.layer.msg("只能选择一个角色查看");
            return;
        }
        selectedRole = checkStatus.data[0];
        $('#roleAuthModal').modal('show');
        $.ajax("/admin/roles/" + checkStatus.data[0].id + "/authes", {
            type: 'GET',
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layui.layer.msg("出错了");
            },
            success: function (data, textStatus, jqXHR) {
                $('#roleAuthContent').html(data);
            }
        });
    }

    // 为modal添加hide 监听
    $('#roleAuthModal').on('hide.bs.modal', function (event) {
        $('#roleAuthContent').html("");
    });

    function delRole(obj, index) {
        // 向服务端发送删除指令
        $.ajax("/admin/roles/" + obj.data.id, {
            type: 'delete',
            dataType: "json", //预期服务器返回的数据类型
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.close(index);
                layer.msg('删除出错了');
            },
            success: function (data, textStatus, jqXHR) {
                obj.del(); // 删除对应行（tr）的DOM结构
                layer.close(index);
                layui.table.reload('roleTable');
            }
        });
    }

    function saveRole() {
        var saveRoleForm = document.getElementById("saveRoleForm");
        // console.log(saveRoleForm);
        var name = saveRoleForm.name;
        if (name.value.length == 0) {
            layer.msg('角色名称是必填项');
            name.focus();
            return;
        }
        var formData = new FormData(saveRoleForm);
        if (saveRoleForm.dataset.op == 'update') { //说明是更新操作
            formData.append("id", saveRoleForm.dataset.roleId);
        }
        $.ajax({ // 向服务器发送数据
            url: saveRoleForm.action,
            type: 'POST',
            dataType: "json", //预期服务器返回的数据类型
            data: formData,
            contentType: false,
            processData: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#saveRoleModal').modal('hide');
            },
            success: function (data, textStatus, jqXHR) {
                $('#saveRoleModal').modal('hide');
                layui.table.reload('roleTable');
            }
        });
    }
</script>
</body>
</html>